//表格用
var tablelist = [];
//请求用  
var data_rule_request = {};
//存储规则容器
var storage_rule_select = []

var storage_rule_select_obj_arr = []

$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		console.log(response);
		createStorageRulesObj(response);
		bruleRead(response);
		console.log(storage_rule_select)
		layui.use(['form'], function () {
			var form = layui.form;
			//使用循环遍历，给下拉列表赋值
			$.each(storage_rule_select, function (index, value) {
				$('#storage_rule').append(new Option(value.name, JSON.stringify(value)));// 下拉菜单里添加元素
			});
			form.render("select");
		});
		for (var i = 0; i < storage_rule_select.length; i++) {
			var storage_rule_select_obj = {}
			// storage_rule_select_obj.value = JSON.stringify(storage_rule_select[i]);
			storage_rule_select_obj.value = storage_rule_select[i].id + "," + storage_rule_select[i].name;
			storage_rule_select_obj.text = storage_rule_select[i].name;
			storage_rule_select_obj_arr.push(storage_rule_select_obj);
		}

		for (var i = 0; i < 10; i++) {
			if (storage_rule_select_obj_arr) {
				createTab();
			} else {
				alert('加载失败，请刷新重试')
			}
		}
	}
});


function createTab() {
	$("#table_page").bootstrapTable('destroy').bootstrapTable({
		data: tablelist,
		dataType: 'json',
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: true,                   //是否显示分页（*）
		sortable: true,                     //是否启用排序
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		search: false,                      //是否显示表格搜索
		strictSearch: true,
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: true,                //是否启用点击选中行
		//height: 500,                      //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
		uniqueId: "dst_port",                     //每一行的唯一标识，一般为主键列
		//showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
		cardView: false,                    //是否显示详细视图
		detailView: false,                  //是否显示父子表
		//得到查询的参数
		onEditableSave: onbRuleEditableSave,
		queryParams: function (params) {
			//这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
			var temp = {
				rows: params.limit,                         //页面大小
				page: (params.offset / params.limit) + 1,   //页码
				sort: params.sort,      //排序列名  
				sortOrder: params.order //排位命令（desc，asc） 
			};
			return temp;
		},

		columns:
			[{
				field: 'ID',
				align: 'center',
				title: 'ID'
			}, {
				field: 'srcip',
				align: 'center',
				title: '源IP地址',
				editable: editable_cn
			}, {
				field: 'dstip',
				align: 'center',
				title: '目的IP地址',
				editable: editable_cn
			}, {
				field: 'src_port',
				align: 'center',
				title: '源端口',
				editable: {
					type: 'number',
					min: 0,
					max:65535
				}
			}, {
				field: 'dst_port',
				align: 'center',
				title: '目的端口',
				editable: {
					type: 'number',
					min: 0,
					max:65535
				}
			}, {
				field: 'proto',
				align: 'center',
				title: '协议',
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "UDP",
						text: "UDP"
					}, {
						value: "TCP",
						text: "TCP"
					}]
				}
			}, {
				field: 'storage_rule',
				align: 'center',
				title: '存储规则',
				editable: {
					type: 'select',
					title: '值类型',
					source: storage_rule_select_obj_arr
				}
			}, {
				field: 'enabled',
				align: 'center',
				title: '使能',
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "start",
						text: "启用"
					}, {
						value: "pause",
						text: "暂停"
					}, {
						value: "continue",
						text: "恢复"
					}, {
						value: "stop",
						text: "停止"
					}]
				}
			}, {
				field: 'id',
				align: 'center',
				title: '操作',
				width: 120,
				align: 'center',
				valign: 'middle',
				formatter: actionFormatterD
			}
			],

	});

}


function isNumberKey(event) {
	var charCode = (event.which) ? event.which : event.keyCode;
	if (charCode != 46 && charCode > 31
		&& (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105))
		return false;
	return true;
}

function onbRuleEditableSave(field, row, rowIndex, oldValue, $el) {
	// alert("字段名：" + field + "，当前值：" + row[field] + "，旧值：" + oldValue + "，顺位：" + rowIndex);
	var data = $("#table_page").bootstrapTable('getData');
	var objChange = data[rowIndex];
	var idChange = objChange.id;
	var arr = data_rule_request.rules_cfg;
	var bruleWeb = {
		"cfgType": "7",
		"cfgName": "storage_flows.json",
		"content": "",
		"syncNodes": "",
	}
	var bruleSave = {
		"cfg_type": 7,
		"rule_max_id": "",
		"rules_cfg": ""
	}
	if (field == "srcip") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].srcip = row[field];
			}
		}
	} else if (field == "dstip") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dstip = row[field];
			}
		}
	} else if (field == "src_port") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].src_port = parseInt(row[field]);
			}
		}
	} else if (field == "dst_port") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dst_port = parseInt(row[field]);
			}
		}
	} else if (field == "proto") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].proto = row[field];
			}
		}
	} else if (field == "storage_rule") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				// arr[i].storage_rule =  JSON.parse(row[field]);
				var changeObj = row[field].split(",")
				arr[i].storage_rule.id = parseInt(changeObj[0]);
				arr[i].storage_rule.name = changeObj[1];

			}
		}
	} else if (field == "enabled") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				// arr[i].enabled = Boolean(row[field]);
				if (row[field] == "start") {
					// arr[i].enabled = JSON.parse(row[field].toLowerCase())
					arr[i].enabled = true
					arr[i].button = "start"
				} else if (row[field] == "stop") {
					arr[i].enabled = false
					arr[i].button = "stop"
				} else if (row[field] == "continue") {
					arr[i].enabled = true
					arr[i].button = "continue"
				} else if (row[field] == "pause") {
					arr[i].enabled = false
					arr[i].button = "pause"
				}
			}
		}

	}
	bruleSave.rules_cfg = arr;
	bruleSave.rule_max_id = data_rule_request.rule_max_id;
	bruleWeb.syncNodes = JSON.stringify(IPS)
	bruleWeb.content = JSON.stringify(bruleSave)
	postQuestSave(bruleWeb);
	layer.msg('修改成功', { icon: 1 });
}


function actionFormatterD(value, row, index) {
	var id = value;
	var result = "";
	result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"DeleteRuleByIds('" + id + "')\" title='删除'><span class='feather-trash-2'></span></a>";
	return result;
}


//新增规则模态框构建
function createbRuleModel() {
	$('#bruleModal').modal('show');

}

layui.config({
	base: 'step-lay/'
}).use(['form', 'step'], function () {
	var $ = layui.$
		, form = layui.form
		, step = layui.step;

	step.render({
		elem: '#stepForm',
		filter: 'stepForm',
		width: '100%', //设置容器宽度
		stepWidth: '750px',
		height: '550px',
		stepItems: [{
			title: '填写'
		}, {
			title: '完成'
		}]
	});


	form.on('submit(formStep)', function (data) {
		step.next('#stepForm');
		return false;
	});

	$('.pre').click(function () {
		step.pre('#stepForm');
	});

	$('.next').click(function () {
		step.next('#stepForm');
	});
})


var field

layui.use(['form', 'layer', 'jquery'], function () {
	var form = layui.form;
	$ = layui.jquery;
	layer = layui.layer;
	//方法提交
	$('#testSubmitBtn').on('click', function (data) {
		form.submit('brule', function (data) { // 注：v2.7.0 新增
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			console.log(data.field)
			// do something
			//protoJson();
			buildbRuleJson();
		});
		return false;
	});

});




//增加/加入一个协议数据规则JSON
function buildbRuleJson() {

	var arrbRule = data_rule_request.rules_cfg;
	var id = data_rule_request.rule_max_id;
	id++;

	var bruleWeb = {
		"cfgType": "7",
		"cfgName": "storage_flows.json",
		"content": "",
		"syncNodes": "",
	}
	var bruleSave = {
		"cfg_type": 7,
		"rule_max_id": "",
		"rules_cfg": ""
	}
	if (id) {
		var brules = {
			"id": "",
			"srcip": "",
			"dstip": "",
			"src_port": "",
			"dst_port": "",
			"proto": "",
			"storage_rule": { "id": "", "name": "" },
			"enabled": true,
			"button": "start"
		}
		brules.id = id;
	} else {
		arrbRule = []
		var brules = {
			"id": "",
			"srcip": "",
			"dstip": "",
			"src_port": "",
			"dst_port": "",
			"storage_rule": { "id": "", "name": "" },
			"proto": "",
			"enabled": true,
			"button": "start"
		}
		id = 0;
		brules.id = 0;
	}
	brules.id = id;
	brules.srcip = field.srcip1 + "." + field.srcip2 + "." + field.srcip3 + "." + field.srcip4;
	brules.dstip = field.dstip1 + "." + field.dstip2 + "." + field.dstip3 + "." + field.dstip4;
	brules.src_port = parseInt(field.src_port);
	brules.dst_port = parseInt(field.dst_port);

	brules.storage_rule.id = JSON.parse(field.storage_rule).id;
	brules.storage_rule.name = JSON.parse(field.storage_rule).name;
	brules.proto = field.proto;

	arrbRule.push(brules);
	bruleSave.rule_max_id = id;
	bruleSave.rules_cfg = arrbRule;
	bruleWeb.syncNodes = JSON.stringify(IPS)
	bruleWeb.content = JSON.stringify(bruleSave);

	//console.log(arrbRule);
	console.log(arrbRule);
	console.log(bruleWeb);

	postQuestSave(bruleWeb);

	alert("新增成功！");
	window.location.reload();
}


//协议数据规则，删除函数
function DeleteRuleByIds(args) {
	var arrbRule = data_rule_request.rules_cfg;
	console.log(arrbRule);
	console.log(args);
	for (var i = 0; i < arrbRule.length; i++) {
		if (arrbRule[i].id == args) {
			arrbRule.splice(i, 1);
		}
	}
	var bruleWeb = {
		"cfgType": "7",
		"cfgName": "storage_flows.json",
		"content": "",
		"syncNodes": "",
	}
	bruleWeb.syncNodes = JSON.stringify(IPS)
	data_rule_request.rules_cfg = arrbRule;
	bruleWeb.content = JSON.stringify(data_rule_request)
	console.log(bruleWeb)
	console.log(arrbRule)

	postQuestSave(bruleWeb);

	window.location.reload();
}

